package com.ylzinfo.ms.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ylzinfo.bigdata.client.model.Token;
import com.ylzinfo.bigdata.common.ResponseEntity;
import com.ylzinfo.bigdata.customClient.ResourceManagerHandle;
import com.ylzinfo.ms.factory.AbstoryEnAndDeFactory;
import com.ylzinfo.ms.factory.EnAndDeSampleFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 调用加密和非加密的封装
 * @Product: IntelliJ IDEA
 * @Author Rogchen rogchen128@gmail.com
 * @Created Date: 2019/4/9 16:01
 **/
@Slf4j
public class HttpClientUtils {
    private static final String AES = "aes";
    private static final String RSA = "rsa";

    private final static ResourceManagerHandle m = new ResourceManagerHandle();


    /**
     * 获取token
     *
     * @param resourceUrl
     * @param client_id
     * @param client_secret
     * @return
     */
    public static String getAccessToken(String resourceUrl, String client_id, String client_secret) {
        //令牌
        Token token = m.getTokenByClientCredit(resourceUrl, client_id, client_secret);
        //业务
        return token.getAccess_token();
    }

    /**
     * 刷新token
     *
     * @param resourceUrl
     * @param client_id
     * @param client_secret
     * @return
     */
    public static String refreshAccessToken(String resourceUrl, String client_id, String client_secret, String refres_token) {
        //令牌
        Token token = m.refreshTokenByClientCredit(resourceUrl, client_id, client_secret, refres_token);
        //业务
        return token.getAccess_token();
    }

    /**
     * @Description 通过用户名密码获取密钥
     * @Author Rogchen
     * @Date 16:59 2019/4/9
     * @Param [resourceUrl, client_id, client_secret, username, password]
     * @Return java.lang.String
     **/
    public static String getAccessTokenWithUP(String resourceUrl, String client_id, String client_secret, String username, String password) {
        //令牌
        Token token = m.getTokenByUserPassword(resourceUrl, client_id, client_secret, username, password);
        //业务
        return token.getAccess_token();
    }

    /**
     * @Description 无加密
     * @Author Rogchen
     * @Date 16:20 2019/4/9
     * @Param [data]
     * @Return com.ylzinfo.bigdata.common.ResponseEntity
     **/
    public static Result runBuilder(BigDataClient data) {
        ResponseEntity res = null;
        if (StringUtils.isNotBlank(data.getParaType()) && StringUtils.isNotBlank(data.getKey())) {
            try {
                Map<String, Object> params = new HashMap();
                AbstoryEnAndDeFactory factory = EnAndDeSampleFactory.switchByType(data.getParaType());
                String p = factory.encoderBase64(JSON.toJSONString(data.getParam()), data.getKey());
                params.put("data", p);
                res = m.getResource(data.getResourceUrl(), data.getToken(), data.getResourceId(), data.getParaType(), params);
                return resToResult(factory, res, data.getKey());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.errorResult(e.getMessage());
            }
        } else {
            res = m.getResource(data.getResourceUrl(), data.getToken(), data.getResourceId(), data.getParam());
            return resToResult(res);
        }
    }


    /**
     * @Description 不加密通过传递参数直接发送请求
     * @Author Rogchen
     * @Date 16:22 2019/4/9
     * @Param [resourceUrl, token, resourceId, param]
     * @Return com.ylzinfo.bigdata.common.ResponseEntity
     **/
    public static Result runBuilder(String resourceUrl, String token, String resourceId, String paramType, String key, Map<String, Object> param) {
        ResponseEntity res = null;
        if (StringUtils.isNotBlank(paramType) && StringUtils.isNotBlank(key)) {
            try {
                Map<String, Object> data = new HashMap();
                AbstoryEnAndDeFactory factory = EnAndDeSampleFactory.switchByType(paramType);
                String p = factory.encoderBase64(JSON.toJSONString(param), key);
                data.put("data", p);
                res = m.getResource(resourceUrl, token, resourceId, paramType, data);
                return resToResult(factory, res, key);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.errorResult(e.getMessage());
            }
        } else {
            res = m.getResource(resourceUrl, token, resourceId, param);
        }
        return resToResult(res, paramType, key);
    }


    private static Result resToResult(ResponseEntity res) {
        return resToResult(null, res, null);
    }

    private static Result resToResult(ResponseEntity res, String paramType, String key) {
        if (StringUtils.isNotBlank(paramType) && StringUtils.isNotBlank(key)) {
            AbstoryEnAndDeFactory factory = EnAndDeSampleFactory.switchByType(paramType);
            return resToResult(factory, res, key);
        }
        return resToResult(res);
    }

    private static Result resToResult(AbstoryEnAndDeFactory factory, ResponseEntity res, String key) {
        if (res == null) {
            return Result.errorResult("无结果返回！");
        }
        List lt = res.getDatas();
        if (lt != null && lt.size() > 0) {
            Result jb = JSON.parseObject((String) lt.get(0), Result.class);
            if (factory != null) {
                String value = (String) jb.getBodyAttr("data");
                String p = factory.decoderBase64(value, key);
                JSONObject jt = JSON.parseObject(p);
                jb.setData(jt);
            }
            return jb;
        }
        return Result.errorResult("无结果返回！");

    }
}
